package com.yjd.comm.asynmsg;

import com.yjd.comm.asynmsg.model.TaskMsgModel;
import com.yjd.comm.util.FrameUtil;
import org.apache.log4j.Logger;

import java.util.List;

/**
 * <b>description</b>：消息处理器 <br>
 * <b>time</b>：2015-1-23下午3:21:31 <br>
 * <b>author</b>： ready likun_557@163.com
 */
public abstract class MsgProcessor implements IMsgProcessor {

	private List<IMsgProcessor> msgProcessors;

	protected Logger logger = Logger.getLogger(this.getClass());

	/**
	 * 验证是否可以处理
	 * 
	 * @param taskMsgModel
	 * @return
	 * @throws Exception
	 */
	protected abstract boolean validate(TaskMsgModel taskMsgModel)
			throws Exception;

	/**
	 * 消息处理
	 * 
	 * @param taskMessageModel
	 * @throws Exception
	 */
	public void process(TaskMsgModel taskMsgModel) throws Exception {
		try {
			if (validate(taskMsgModel)) {
				onProcess(taskMsgModel);
				if (this.msgProcessors != null
						&& this.msgProcessors.size() >= 1) {
					for (IMsgProcessor mpr : msgProcessors) {
						mpr.process(taskMsgModel);
					}
				}
			}
		} catch (Exception e) {
			logger.error("消息处理失败:" + FrameUtil.json(taskMsgModel), e);
			throw e;
		}
	}

	/**
	 * 处理消息
	 * 
	 * @param msgModel
	 * @throws Exception
	 */
	protected void onProcess(TaskMsgModel taskMsgModel) throws Exception {
		this.getMsgProcessorService().process(taskMsgModel);
	}

	public List<IMsgProcessor> getMsgProcessors() {
		return msgProcessors;
	}

	public void setMsgProcessors(List<IMsgProcessor> msgProcessors) {
		this.msgProcessors = msgProcessors;
	}

	public abstract IMsgProcessorService getMsgProcessorService();
}
